package com.sh.domain.demo.service.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sh.common.constant.GlobalMessage;
import com.sh.common.error.SystemException;
import com.sh.common.model.PageModel;
import com.sh.domain.demo.dao.DemoDao;
import com.sh.domain.demo.dto.DemoPageDto;
import com.sh.domain.demo.dto.DemoSaveDto;
import com.sh.domain.demo.entity.DemoEntity;
import com.sh.domain.demo.service.DemoService;
import com.sh.util.ResourceUtil;

/**
 * 
 * NOTE： DemoServiceImpl
 *
 * @author： king
 * @date： 2019年4月2日
 *
 */
@Service
public class DemoServiceImpl implements DemoService {

	private static final Logger log = Logger.getLogger(DemoServiceImpl.class);
	
	@Autowired
	private DemoDao demoDao;
	
	@Override
	public PageModel findDemoByPage(DemoPageDto demoDto) {
		
		log.info(demoDto);
		PageModel page = new PageModel(demoDto.getPage());
		
		List<DemoEntity> list = demoDao.findDemoByPage(demoDto, page.getStart(), page.getRows());
		Long total = demoDao.findDemoCount(demoDto);
		
		page.setData(list);
		page.setTotal(total.longValue());
		
		log.info(page);
		
		return page;
	}
	
	@Override
	public List<DemoEntity> findDemoList(DemoPageDto demoDto){
		
		List<DemoEntity> list = demoDao.findDemoList(demoDto);
		
		return list;
	}

	@Override
	public DemoEntity findDemoById(String id) {
		
		DemoEntity demoEntity = demoDao.getDemoById(id);
		
		if(demoEntity == null) {
			
			throw new SystemException(GlobalMessage.NO_EXESIT.code, GlobalMessage.NO_EXESIT.i18n);
		}
		
		return demoEntity;
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public void save(DemoSaveDto demoSaveDto) {
		
		DemoEntity demoEntity = new DemoEntity();
		
		BeanUtils.copyProperties(demoSaveDto, demoEntity);
		demoEntity.setId(ResourceUtil.getUUID());
		
		demoDao.add(demoEntity);
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public void update(DemoSaveDto demoSaveDto) {
		
		DemoEntity demoEntity = demoDao.getDemoById(demoSaveDto.getId());
		
		if(demoEntity == null) {
			
			throw new SystemException(GlobalMessage.NO_EXESIT.code, GlobalMessage.NO_EXESIT.i18n);
		}
		
		BeanUtils.copyProperties(demoSaveDto, demoEntity);
		
		demoDao.update(demoEntity);
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public void delete(String id) {

		DemoEntity demoEntity = demoDao.getDemoById(id);
		
		if(demoEntity == null) {
			
			throw new SystemException(GlobalMessage.NO_EXESIT.code, GlobalMessage.NO_EXESIT.i18n);
		}
	
		demoDao.detele(demoEntity);
	}

}
